from flask import Flask, request, jsonify
import os
from datetime import datetime
from data_loader import PCFDataLoader
import json

app = Flask(__name__)

# Initialize data loader
data_loader = PCFDataLoader()

@app.route('/service/user/PcfSubscription', methods=['GET'])
def pcf_subscription():
    """PCF Subscription API endpoint"""
    msisdn = request.args.get('number')
    
    if not msisdn:
        return jsonify({
            "code": 400,
            "message": "Missing required parameter: number",
            "result": None
        }), 400
    
    # Try to load the data file directly for the MSISDN
    data_file = os.path.join('data', f'{msisdn}.json')
    if os.path.exists(data_file):
        try:
            with open(data_file, 'r', encoding='utf-8') as f:
                demo_data = json.load(f)
            if not isinstance(demo_data, list):
                demo_data = []
        except Exception as e:
            demo_data = []
    else:
        demo_data = []
    
    # Construct the response in the same format as the sample
    response = {
        "code": 200,
        "message": "操作成功",
        "result": {
            "records": demo_data,
            "total": 0,
            "size": 10,
            "current": 1,
            "orders": [],
            "optimizeCountSql": True,
            "hitCount": False,
            "countId": None,
            "maxLimit": None,
            "searchCount": True,
            "pages": 0
        }
    }
    
    return jsonify(response)

@app.route('/health', methods=['GET'])
def health_check():
    """Health check endpoint"""
    return jsonify({
        "status": "healthy",
        "service": "PCF API Server Demo",
        "timestamp": datetime.now().isoformat()
    })

@app.route('/', methods=['GET'])
def root():
    """Root endpoint with API information"""
    return jsonify({
        "service": "PCF API Server Demo",
        "version": "1.0.0",
        "endpoints": {
            "pcf_subscription": "/service/user/PcfSubscription?number=<msisdn>",
            "health": "/health"
        },
        "sample_msisdns": data_loader.get_available_msisdns()
    })

@app.route('/msisdns', methods=['GET'])
def list_msisdns():
    """List all available MSISDNs"""
    return jsonify({
        "available_msisdns": data_loader.get_available_msisdns(),
        "total_count": len(data_loader.get_available_msisdns())
    })

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 1026))
    app.run(host='0.0.0.0', port=port, debug=True) 